import { ref } from "vue";
import { defineStore } from "pinia";
import { MenuServiceImpl } from "@/business/service/menu.service";
import type { Menu } from "@/business/entity/menu.entity";
import router from "@/router";
import type { RouteRecordNormalized } from "vue-router";

export const useMenuStore = defineStore("menuStore", () => {
  const menus = ref<Array<Menu>>([]);
  let isCollapse = ref<boolean>(false);
  const routes: RouteRecordNormalized[] = router.getRoutes();
  const getMenu = () => {
    const menuService: MenuServiceImpl = new MenuServiceImpl();
    const menusList: Array<Menu> = menuService.getMenus();
    menus.value = menusList;
    getMenuList(menusList, "");
    console.log(router.getRoutes())
    return menus.value;
  };

  // 递归遍历menusList
  const getMenuList = (menusList: Array<Menu>, index: string) => {
    for (let i = 0; i < menusList.length; i++) {
      // @ts-ignore
      const menu: Menu = menusList.at(i);
      menu.index = index === "" ? i + 1 + "" : index + "-" + (i + 1);
      // @ts-ignore
      const currentRouter: RouteRecordNormalized = routes.find((route:RouteRecordNormalized)  => route.name === menu.name);
      menu.path = currentRouter.path;
      // @ts-ignore
      currentRouter.meta = menu.meta;

      // 判断是否有子级菜单
      if (menu.children.length > 0) {
        // 获取当前菜单，第1个子级菜单对应的路由
        // @ts-ignore
        const childRouter:RouteRecordNormalized = routes.find((route:RouteRecordNormalized)  => route.name === menu.children.at(0).name);
        // 获取当前菜单，第1个子级菜单对应的路由的父级路由，并设定路由跳转
        // @ts-ignore
        const parentRouter:RouteRecordNormalized = routes.find((route:RouteRecordNormalized) => childRouter.path.substring(0, childRouter.path.lastIndexOf("/")) === route.path);
        parentRouter.redirect = childRouter.path;
        getMenuList(menu.children, index === "" ? i + 1 + "" : index + "-" + (i + 1));
      }
    }
  };

  const setCollapse = (collapse: boolean) => {
    isCollapse.value = collapse;
  };

  const getCollapse = () => {
    return isCollapse.value;
  };

  return { getMenu, menus, setCollapse, getCollapse, isCollapse };
});
